﻿using System;
using System.Linq;
using System.Web.Mvc;
using CP_SchoolForChildren_v0._1.Controllers.Support;
using CP_SchoolForChildren_v0._1.Models.DataModel;

namespace CP_SchoolForChildren_v0._1.Controllers.BE
{
    public class ServiceManagementController : Controller
    {
        private FunctionController fc = new FunctionController();
        private SFCMessage sfcMessage = new SFCMessage();
        //
        // GET: /Service/

        [Authorize(Roles = "Admin")]
        public ActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public JsonResult ListService(string keywords, int jtStartIndex, int jtPageSize, string jtSorting)
        {
            try
            {
                if (keywords == null)
                    keywords = "";
                //Get Data
                var record = from svr in fc.db.Services
                             where svr.ServiceID != 1
                             where svr.ServiceName.Contains(keywords)
                             select new
                                        {
                                            ServiceID = svr.ServiceID,
                                            ServiceName = svr.ServiceName,
                                            Weight = svr.Weight,
                                            SchoolCount = svr.SchoolServices.Count
                                        };
                //Get Totalrow
                var totalrow = record.Count();
                //Paging
                var temp = record.OrderUsingSortExpression(jtSorting).
                    Skip(jtStartIndex).Take(jtPageSize);
                return Json(new {Result = "OK", Records = temp.ToList(), TotalRecordCount = totalrow});
            }
            catch (Exception ex)
            {
                return Json(new {Result = "ERROR", Message = ex.ToString()});
            }
        }

        [HttpPost]
        public JsonResult CreateService(Service service)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return Json(new
                                    {
                                        Result = "ERROR",
                                        Message = "Form is not valid! " +
                                                  "Please correct it and try again."
                                    });
                }
                if (!CheckNewService(service))
                {
                    return Json(new
                                    {
                                        Result = "ERROR",
                                        Message = "Dữ liệu đã tồn tại"
                                    });
                }
                var record = fc.db.Services.Add(service);
                fc.db.SaveChanges();
                return Json(new {Result = "OK", Record = record});
            }
            catch (Exception ex)
            {
                return Json(new {Result = "ERROR", Message = ex.ToString()});
            }
        }

        [HttpPost]
        public JsonResult UpdateService(Service service)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return Json(new {Result = "ERROR", Message = "Form is not valid! Please correct it and try again."});
                }
                if (!CheckService(service))
                {
                    return Json(new
                                    {
                                        Result = "ERROR",
                                        Message = "Dữ liệu đã tồn tại"
                                    });
                }
                fc.db.Entry(service).State = System.Data.EntityState.Modified;
                var record = fc.db.SaveChanges();
                return Json(new {Result = "OK", Record = record});
            }
            catch (Exception ex)
            {
                return Json(new {Result = "ERROR", Message = ex.ToString()});
            }
        }

        [HttpPost]
        public JsonResult DeleteService(Service service)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return Json(new {Result = "ERROR", Message = "Form is not valid! Please correct it and try again."});
                }

                if (CheckServiceFK(service))
                {
                    return Json(new { Result = "ERROR", Message = sfcMessage.ForeginKey });
                }
                fc.db.Entry(service).State = System.Data.EntityState.Deleted;
                var record = fc.db.SaveChanges();
                return Json(new {Result = "OK", Record = record});
            }
            catch (Exception ex)
            {
                return Json(new {Result = "ERROR", Message = ex.ToString()});
            }
        }

        // Delete all row in SchoolService
        public bool CheckServiceFK(Service service)
        {
                var query = from svr in fc.db.SchoolServices
                            where svr.ServiceID == service.ServiceID
                            select svr;
                if (query.Any())
                    return true;
            return false;
        }

        // Check dupplicate name
        public bool CheckService(Service service)
        {
            var record = fc.db.Services.
                Where(s => s.ServiceID != service.ServiceID).
                Where(s => s.ServiceName == service.ServiceName).
                ToList();
            if (record.Any())
                return false;
            return true;
        }

        public bool CheckNewService(Service service)
        {
            var record = fc.db.Services.
                Where(c => c.ServiceName == service.ServiceName).ToList();
            if (record.Any())
                return false;
            return true;
        }
    }
}